import React from 'react';
import { Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import './style.less';

export interface PageLoadingProps {
  tip?: string;
  size?: 'small' | 'default' | 'large';
  delay?: number;
  spinning?: boolean;
  fullScreen?: boolean;
  transparent?: boolean;
  children?: React.ReactNode;
  className?: string;
  style?: React.CSSProperties;
}

const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;

const PageLoading: React.FC<PageLoadingProps> = ({
  tip = '加载中...',
  size = 'large',
  delay = 0,
  spinning = true,
  fullScreen = false,
  transparent = false,
  children,
  className = '',
  style,
}) => {
  const loadingNode = (
    <Spin
      indicator={antIcon}
      tip={tip}
      size={size}
      delay={delay}
      spinning={spinning}
      className={`page-loading ${transparent ? 'page-loading-transparent' : ''} ${className}`}
      style={style}
    >
      {children}
    </Spin>
  );

  if (fullScreen) {
    return (
      <div className="page-loading-fullscreen-wrapper">
        {loadingNode}
      </div>
    );
  }

  return loadingNode;
};

// 创建一个全屏加载的快捷方式
export const FullScreenLoading: React.FC<Omit<PageLoadingProps, 'fullScreen'>> = (props) => (
  <PageLoading fullScreen {...props} />
);

// 创建一个包装组件的高阶组件
export const withLoading = <P extends object>(
  WrappedComponent: React.ComponentType<P>,
  loadingProps?: Omit<PageLoadingProps, 'children' | 'spinning'>
) => {
  return function WithLoading({
    loading = false,
    ...props
  }: P & { loading?: boolean }) {
    return (
      <PageLoading spinning={loading} {...loadingProps}>
        <WrappedComponent {...(props as P)} />
      </PageLoading>
    );
  };
};

// 创建一个延迟加载组件的包装器
export const DelayLoading: React.FC<PageLoadingProps> = (props) => (
  <PageLoading delay={200} {...props} />
);

// 创建一个带有骨架屏的加载组件
export const SkeletonLoading: React.FC<{
  loading?: boolean;
  children: React.ReactNode;
  skeleton: React.ReactNode;
}> = ({ loading = true, children, skeleton }) => {
  if (loading) {
    return <>{skeleton}</>;
  }
  return <>{children}</>;
};

export default PageLoading;